package com.km.noh.weatherinfo.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.util.Log;

public class KMServerNetwork {
	
	public static final int HTTP_TIMEOUT = 5000;
	
	private String xmlValue = null;
	private String fileLength = null;
	private String fileName = null;
	
	/**
	 * XML에서 원하는 값을 추출한다. Level1만 지원함.
	 * @param str
	 * @return
	 */
	public String parser(String str) {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			InputStream istream = new ByteArrayInputStream(xmlValue.getBytes("EUC-KR"));
			Document doc = builder.parse(istream);

			Element order = doc.getDocumentElement();
			NodeList items = order.getElementsByTagName(str);
			Node item = items.item(0);
			if (item==null) return null;
			Node text = item.getFirstChild();
			String ItemName = text.getNodeValue();
			
			return ItemName;
			
		} catch (Exception e) {
			Util.logError(e);
		}
		return null;
	}
	
	public Element getParser() {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			InputStream istream = new ByteArrayInputStream(xmlValue.getBytes());
			Document doc = builder.parse(istream);

			Element order = doc.getDocumentElement();
			return order;
			
		} catch (Exception e) {
			Util.logError(e);
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public String getData(String url, Map<String, String> headers, Map<String, String> params, boolean isPostType) throws Exception {
		return getData(url, headers, new Map[]{params}, isPostType);
	}
	
	public String getData(String url, Map<String, String> headers, Map<String, String>[] params, boolean isPostType) throws Exception {
		
		StringBuilder sb = new StringBuilder();
		InputStream is = null;
		DefaultHttpClient httpclient = null;
		BufferedReader reader = null;
		try {
			httpclient = new DefaultHttpClient();
			
			HttpParams httpParams = httpclient.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, HTTP_TIMEOUT);

			HttpResponse response = null;

			if (params != null && isPostType) {
				HttpPost httpPost = new HttpPost(url);
    			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    			for (int i=0;i<params.length;i++) {
					for (Map.Entry<String, String> entry: params[i].entrySet()) {	
		        		nameValuePairs.add(new BasicNameValuePair(entry.getKey(), (String)entry.getValue()));
		        		Util.log("param :: "+ entry.getKey() +"="+entry.getValue());
					}
    			}
    			UrlEncodedFormEntity entityRequest = new UrlEncodedFormEntity(nameValuePairs, "EUC-KR");
    			httpPost.setEntity(entityRequest);
    			if (headers != null) {
			        for (Map.Entry<String, String> entry2: headers.entrySet()) {
			        	httpPost.addHeader(entry2.getKey(), entry2.getValue());
			        	Util.log("header :: "+entry2.getKey()+"="+ entry2.getValue());
			        }
				}
    			response = httpclient.execute(httpPost);
			} else {
				if (params != null) {
					if (params[0].entrySet().size() > 0) url += "?";
					for (Map.Entry<String, ?> entry : params[0].entrySet()) {
						if (entry.getValue() instanceof String[]) {
							String[] values = (String[]) entry.getValue();
							for (int i = 0; i < values.length; i++) {
								url += entry.getKey() + "=" + values[i] + "&";
							}
						} else {
							url += entry.getKey() + "=" + entry.getValue() + "&";
						}
					}
				}

		        HttpGet httpget = new HttpGet(url);
		        Util.log("network", "url = "+url);
				if (headers != null) {
			        for (Map.Entry<String, String> entry2: headers.entrySet()) {
			        	httpget.addHeader(entry2.getKey(), entry2.getValue());
			        }
				}
				response = httpclient.execute(httpget);
			}
			
			is = response.getEntity().getContent();
			
			reader = new BufferedReader(new InputStreamReader(is, "EUC-KR"), 8);
			
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line).append("\n");
			}
			
		} catch (Exception e) {
			Util.logError(e);
			throw e;
		} finally {
			try {
				if (is != null) is.close();
				if (reader != null) reader.close();

			} catch (Exception e) {throw e;}
		}
		
		xmlValue = sb.toString();
		Log.d("debug", "url = " + url);
		Log.d("debug", xmlValue);
		return xmlValue;
	}
	
	public int getFileLength() {
		int size = 0;
		try {
			size = Integer.parseInt(fileLength);
		}catch (Exception e) {}
		return size;
	}
	
	public String getFileName() {
		return fileName;
	}
	
}
